<template>
	<view>
		<view class="uni-list">
			<uni-forms class="bg_color" ref="valiForm" :rules="rules">
				<view class="forms_border">
					<uni-forms-item label="姓名" required name="name">
						<view class="card_number">
							<uni-easyinput placeholder="请输入姓名" :clearable="false" :inputBorder="false"
								v-model="valiFormData.name" />
						</view>
					</uni-forms-item>
				</view>
				<view class="forms_border">
					<uni-forms-item class="form_list" label="手机号" required name="phone">
						<view class="card_number">
							<uni-easyinput placeholder="请输入手机号" :clearable="false" :inputBorder="false" type="number"
								v-model="valiFormData.phone" />
						</view>
					</uni-forms-item>
				</view>
				<view class="forms_border">
					<uni-forms-item class="form_list" style="display:flex;" required label="省市区" name="provinceArea">
						<view class="ui-list" @click.stop="pickerChange">
							<uni-easyinput placeholder="请选择省市区" :clearable="false" :inputBorder="false"
								style="display:inline-block" type="number" v-model="valiFormData.region" />
							<view style="height: 50rpx; line-height: 50rpx;display:inline-block;">
								<image style="width: 40rpx; height: 30rpx; margin-top: 12rpx;"
									src="../../static/images/icon_gray.png"></image>
							</view>
						</view>

					</uni-forms-item>
				</view>
				<view class="forms_border">
					<uni-forms-item class="form_list" label="具体地址" required name="address">
						<view>
							<uni-easyinput type="textarea" maxlength="40" :clearable="false" :inputBorder="false"
								v-model="valiFormData.address" />
						</view>
					</uni-forms-item>
				</view>
				<uni-forms-item class="form_list" label="设置默认" name="address">
					<view class="defaultBtn">
						<switch :checked="valiFormData.defaultFlag=='0'" color="#4ccdbc"
							style="margin-top: -8rpx; transform: scale(0.8);" @change="setDefault" />
					</view>
				</uni-forms-item>
				<!-- </view> -->
			</uni-forms>
		</view>
		<button :disabled="extraction1" v-if="valiFormData.id" class="arc_button btn_address" style="width: 90%;"
			@click="submit('valiForm')" type="primary">
			保存
		</button>

		<button :disabled="extraction2" v-else class="arc_button btn_address" style="width: 90%;"
			@click="submit2('valiForm')" type="primary">
			添加
		</button>
	</view>
</template>

<script>
	// import address from '@/static/json/allAddress.json' // json文件中获取的地址数据
	import {
		addressDetails,
		addAddress,
		updateAddress,

		// getHospitalProvince,
		// getCity,
		// getCountyCity
	} from '@/api/prescribing.js'
	import store from '../../store'
	export default {
		data() {
			return {
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空',
						}, ],
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空',
						}, ],
					},
					provinceArea: {
						rules: [{
							required: true,
							errorMessage: '省市区不能为空',
						}, ],
					},
					address: {
						rules: [{
							required: true,
							errorMessage: '具体地址不能为空',
						}, ],
					},
				},
				valiFormData: {
					uid: store.state.app.uid,
					name: '',
					phone: '',
					// province: '',
					// city: '',
					region: '',
					address: '', //详细地址
					// provinceArea: '',
					longitude: '', // 经度
					latitude: '', //纬度
					defaultFlag: '1', // 是否设置为默认地址
				}, //列表数据

				extraction1: false,
				extraction2: false,
				mapAddressFlag: false, //
				orderid: 0, //订单ID
			}
		},
		onLoad(options) {
			if (options.id) {
				this.getDetails(options.id)
			}

		},
		methods: {
			// 设置默认地址
			setDefault(e) {
				if (e.target.value) {
					this.valiFormData.defaultFlag = '0' //0是默认选中
				} else {
					this.valiFormData.defaultFlag = '1' //1 不选中
				}
			},
			// 省市区确认事件
			pickerChange(name, value) {
				let that = this;
				uni.authorize({
					scope: 'scope.userLocation',
					success: function(
						scope
					) {

						that.getMapLocation();
					},
					fail: function(
						fail) {

						uni.showToast({
							title: "授权失败,无法授权您的位置权限",
							icon: "none",
							duration: 1000
						})
					}
				})


			},
			getMapLocation() {

				uni.chooseLocation({
					success: (res) => {
						this.mapAddressFlag = true
						// this.mapAddress = res.address + res.name;
						console.log(res, '获取的地址信息');
						var reg = /.+?(省|市|自治区|自治州|县|区)/g // 省市区的正则
						let region = res.address.match(reg).toString().replace(/,/g, '')
						this.valiFormData.region = region
						this.valiFormData.address = res.name
						this.valiFormData.longitude = res.longitude // 经度
						this.valiFormData.latitude = res.latitude //纬度

						/**
						 *  address: "山东省潍坊市奎文区胜利东街4889号(胜利东街与虞河路交叉路口东北角)"
						    errMsg: "chooseLocation:ok"
						    latitude: 36.707503
						    longitude: 119.135719
						    name: "东方名苑 "
						 */

					},
					fail: (err) => {

						console.log(JSON.stringify(err), 'err----');
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								console.log(res, 're----');
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.authorize({
													scope: 'scope.userLocation',
													success: function(
														scope
													) {

														uni.openSetting({
															success: (
																data
															) => {
																// 如果用户授权了地理信息在，则提示授权成功
																if (data
																	.authSetting[
																		'scope.userLocation'
																	] ===
																	true
																) {
																	uni.showToast({
																		title: "授权成功",
																		icon: "success",
																		duration: 1000
																	})
																	// 授权成功后，然后再次chooseLocation获取信息
																	uni.chooseLocation({
																		success: (
																			res
																		) => {
																			console
																				.log(
																					"详细地址",
																					res
																				);
																			this.mapAddressFlag =
																				true
																			// this.mapAddress = res.address + res.name;
																			console
																				.log(
																					res,
																					'获取的地址信息'
																				);
																			var reg =
																				/.+?(省|市|自治区|自治州|县|区)/g // 省市区的正则
																			let region =
																				res
																				.address
																				.match(
																					reg
																				)
																				.toString()
																				.replace(
																					/,/g,
																					''
																				)
																			this.valiFormData
																				.region =
																				region
																			this.valiFormData
																				.address =
																				res
																				.name
																			this.valiFormData
																				.longitude =
																				res
																				.longitude // 经度
																			this.valiFormData
																				.latitude =
																				res
																				.latitude //纬度
																			// this.getRegionFn(res);
																		}
																	})
																} else {
																	uni.showToast({
																		title: "授权失败",
																		icon: "none",
																		duration: 1000
																	})
																}
															}
														})
													},
													fail: function(
														fail) {

														uni.showToast({
															title: "授权失败,无法授权您的位置权限",
															icon: "none",
															duration: 1000
														})
													}
												})



											}
										},
										complete: (complete) => {
											console.log(complete,
												'完成999---')
											if (!complete.confirm) {
												uni.showToast({
													title: "授权失败，无法获取您的位置",
													icon: "none",
													duration: 1000
												})
											}

										},
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					},

				});
			},

			goto(url) {
				uni.navigateTo({
					url: url,
				})
			},
			getDetails(id) {
				uni.showLoading({
					title: '加载中',
				})
				// console.log(id);
				addressDetails(id)
					.then((res) => {
						// console.log("^^^^^^地址详情", JSON.stringify(res.data))
						this.valiFormData = res.data
						complete: (complete) => {},

							uni.hideLoading()
					})
					.catch((res) => {
						uni.hideLoading()
						// console.log(res);
					})
			},

			// 保存
			submit(ref) {
				this.extraction1 = true
				uni.showLoading({
					title: '加载中',
				})

				this.$refs[ref].validate((valid) => {
					uni.hideLoading()
					if (valid == null) {
						this.valiFormData.uid = store.state.app.uid; //默认地址需要传uid，后端根据uid判断地址列表中设置默认项
						updateAddress(this.valiFormData)
							.then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: `修改成功`,
									})
									console.log(this.mapAddressFlag, '标识999----')
									if (this.mapAddressFlag) {
										setTimeout(function() {
											uni.navigateBack({
												delta: 1 // 返回上一级页面。
											})
										}, 1000)
									} else {
										setTimeout(function() {
											uni.navigateBack()
										}, 1000)
									}

									this.extraction1 = false
								} else {
									uni.showToast({
										title: `修改失败`,
										icon: `error`,
									})
									this.extraction1 = false
								}
							})
							.catch((err) => {
								// console.log('err', err);
								uni.showToast({
									title: err,
									icon: `error`,
								})
								this.extraction1 = false
							})
					}
				})
			},
			// 添加
			submit2(ref) {
				this.extraction2 = true
				uni.showLoading({
					title: '加载中',
				})
				this.$refs[ref].validate((valid) => {
					uni.hideLoading()
					if (valid == null) {
						addAddress(this.valiFormData)
							.then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: `新增成功`,
									})
									// console.log(this.mapAddressFlag, '标识888999----')

									if (this.mapAddressFlag) {
										setTimeout(function() {
											uni.navigateBack({
												delta: 1 // 返回上一级页面。
											})
										}, 1000)
									} else {
										setTimeout(function() {
											uni.navigateBack()
										}, 1000)
									}

									this.extraction2 = false
								} else {
									uni.showToast({
										title: `新增失败`,
										icon: `error`,
									})
									this.extraction2 = false
								}
							})
							.catch((err) => {
								// console.log('err', err);
								uni.showToast({
									title: err,
									icon: `error`,
								})
								this.extraction2 = false
							})
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	/deep/.uni-forms-item__label.data-v-61dfc0d0 {
		width: 170rpx !important;
	}

	/deep/.uni-forms-item__label .label-text.data-v-61dfc0d0 {
		font-size: 30rpx;
		color: #333;
	}

	/deep/.uni-easyinput__content-input.data-v-abe12412 {
		font-size: 30rpx;
	}

	/deep/.uni-forms-item.data-v-61dfc0d0 {
		padding: 8rpx 5rpx;
	}

	/deep/.uni-easyinput-error.data-v-abe12412 {
		padding-bottom: 24rpx;

	}

	/deep/.data-v-abe12412 {
		width: 450rpx !important;
	}

	/deep/.is-textarea {
		height: 140rpx !important;
	}

	.forms_border {
		border-bottom: 1rpx solid #ededed;
	}

	.uni-list {
		margin-bottom: 30rpx;
		background-color: #fff;
		position: relative;
		width: 100%;
		display: -webkit-box;
		padding: 20rpx 30rpx;
		display: flex;
		-webkit-box-orient: vertical;
		-webkit-box-direction: normal;
		flex-direction: column;
	}

	.uni-list-cell-pd {
		padding: 22rpx 30rpx;
	}

	.card_number {
		display: flex;
		/* float: right; */
	}

	.popup {
		height: fit-content;
		width: 100%;
		background: #fff;
	}

	.picker-btn {
		display: flex;
		height: 100upx;
		width: 100%;
		line-height: 100upx;
		background: #fff;
		font-size: 34upx;
		z-index: 1;
		border-bottom: 1rpx solid #f8f8f8;
	}

	.left {
		color: #888888;
		padding-left: 80rpx;
		box-sizing: border-box;
	}

	.right {
		flex: 1;
		text-align: right;
		padding-right: 40upx;
		color: #007aff;
		box-sizing: border-box;
	}

	picker-view {
		width: 100%;
		height: 500rpx;
		display: relative;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	/deep/.uni-forms-item__inner.data-v-61dfc0d0 {
		padding-bottom: 0 !important;
	}

	.defaultBtn {
		float: right;
		margin-right: 40rpx;
		margin-top: 20rpx;
	}

	.btn_address {
		background: -webkit-linear-gradient(#77e2a4, #4ccdbc);
		color: #ffffff;
	}

	// /deep/.data-v-57ffe7be .uni-forms-item__label .label-text.data-v-61dfc0d0 {
	// 	font-size: 33rpx;
	// }
	/deep/.data-v-57ffe7be .uni-easyinput__content-input.data-v-abe12412 {
		font-size: 30rpx;
	}

	/deep/.uni-forms-item__content.data-v-61dfc0d0 {
		font-size: 30rpx;
	}

	/deep/.uni-easyinput__content-textarea.data-v-abe12412 {
		font-size: 30rpx;
		padding-left: 23rpx;
	}
</style>